<?php
namespace PHPSpring\Annotation\Impl;

use PHPSpring\Annotation\IValidator;

/**
 * @Length($min, $max, $message?, array|string $groups?)
 * eg:
 *   @Length(min=1, max=3)
 *   @Length(min=1, max=3, message='message') or @Length(min=1, max=3, 'message')
 *   @Length(min=1, max=3, message='message', groups='groups') or @Length(min=1, max=3, 'message', groups='groups')
 * message format: '%s长度%min ~ %max' => '$fieldName长度$min ~ $max'
 */

class Length implements IValidator {

  public static function validate ($args, $fieldName, $fieldType, $fieldValue, $group=null) {
    $error = self::normalizeArguments($args);
    if ($error) {
      return $error;
    }
    if (Validation::skipValidateByGroup($group, $args)) {
      return;
    }
    $min = $args['min'];
    $max = $args['max'];
    $error = false;
    $strLen = strlen($fieldValue);//not mb
    if (($strLen < $min) || ($strLen > $max)) {
      $error = true;
    }
    if ($error) {
      return self::getMessage($fieldName, $fieldValue, $min, $max, $args[Validation::MESSAGE_ARG_KEY]);
    }
  }

  public static function normalizeArguments (array &$args) {
    Validation::resetMessageArgs($args, '%s 必填');
    if(!isset($args['min']) || !isset($args['max'])) {
      return 'Length验证器参数缺失：$min, $max';
    }
    $min = $args['min'];
    $max = $args['max'];
    if (!is_numeric($args['min']) || !is_numeric($args['max'])) {
      return "Length验证器参数不合法：min: $min, max: $max";
    }
    $min = $min - 0;
    $max = $max - 0;
    if ($min >= $max) {
      return "Length验证器参数不合法：min: $min, max: $max";
    }
    $args['min'] = $min;
    $args['max'] = $max;
  }

  private static function getMessage ($fieldName, $fieldValue, $min, $max, $message) {
    $message = str_replace('%s', $fieldName, $message);
    $message = str_replace('%min', $min, $message);
    $message = str_replace('%max', $max, $message);
    return $message;
  }

}
